<template>
  <div>
    <template v-if="viewData.id">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5" v-for="btn in viewData.buttons.filter(b => b.position == 'top')" :key="btn.id">
          <rva-list-top-button
              :viewButtonData="btn" :disabled="isButtonDisabled(btn)" :selection="selection"
              @rva-button-click="handleButtonClick" :requestParams="requestParams"
          ></rva-list-top-button>
        </el-col>
        <right-toolbar :showSearch.sync="queryParams.showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="listData" @selection-change="handleSelectionChange"
                @header-click="handleHeaderCLick"
                :header-cell-class-name="handleHeaderClass"
                @sort-change="handleSortChange"
                style="width: 100%" >
        <el-table-column type="selection" width="55" align="center" fixed/>
        <template v-for="p in viewData.properties">
          <el-table-column
              v-if="p.type == 'button'"
              :label="p.name" align="center" class-name="small-padding fixed-width"
              :key="p.id" fixed="right" :width="getPropButtonSize(p) * 75" scoped-slot
          >
            <template slot="header">
              <rva-list-config :prop="p"></rva-list-config>
            </template>
            <template slot-scope="scope">
              <el-row>
                <el-col v-for="(btn, btnIndex) in getPropButtons(p, scope.row)" :span="getPropButtonColSpan(p, scope.row)"
                        v-if="getPropButtons(p, scope.row).length <= 4 || btnIndex < 3" :key="p.id + '-' + btn.id">
                  <rva-list-inner-button
                      :viewButtonData="btn"
                      :selection="[scope.row]"
                      :requestParams="requestParams"
                      @rva-button-click="handleButtonClick"
                  ></rva-list-inner-button>
                </el-col>
                <el-col :span="6" v-if="getPropButtons(p, scope.row).length > 4">
                  <el-dropdown>
                    <el-button type="text" size="mini">
                      更多<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item v-for="(btn, btnIndex) in getPropButtons(p, scope.row)" :key="p.id + '-' + btn.id"
                        v-if="btnIndex > 2">
                        <rva-list-inner-button
                            :viewButtonData="btn"
                            :selection="[scope.row]"
                            :requestParams="requestParams"
                            @rva-button-click="handleButtonClick"
                        ></rva-list-inner-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column
              v-else :key="p.id" align="center" :label="p.name" :prop="p.id"
              :sort-orders="orders" :sortable="p.listOrderIdx >= 0 ? 'custom' : false"
              :width="p.width" show-overflow-tooltip scoped-slot
          >
            <template slot="header">
              <rva-list-config :prop="p"></rva-list-config>
            </template>
          </el-table-column>
        </template>
      </el-table>

      <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
      />
    </template>
  </div>
</template>

<script>

import RvaFormView from "@/components/rva/form";
import RvaListViewTopButton from "@/components/rva/list/button/top";
import RvaListViewInnerButton from "@/components/rva/list/button/inner";
import RvaListConfig from "@/components/rva/list/config"; // 如果el-column上使用render-header，则RvaListConfig必须在vue中全局注册才能使用

import { listCrud, listColumn, handleRvaButtonClick , getRvaViewData} from "@/api/rva/crud";
import { RvaUtils } from "@/api/rva/util";

import RvaButtonConfig from "@/components/rva/button/config";
import Vue from "vue";

Vue.component('rva-button-config', RvaButtonConfig)

export default {
  name: "RvaListView",
  props: ['viewId', 'queryParams', 'requestParams'],
  components: {
    "rva-form": RvaFormView,
    "rva-list-top-button": RvaListViewTopButton,
    "rva-list-inner-button": RvaListViewInnerButton,
    "rva-list-config": RvaListConfig
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      buttonLoading: false,
      // 当列表点击时，列表上面按钮是否禁用
      buttonDisabled: {},
      // 选中数组
      selection: [],
      // 总条数
      total: 0,
      viewData: {},
      // 模块表格数据
      listData: [],
      orders: ['descending', 'ascending', null],
      orderByList:[]
    };
  },
  created() {
    this.reloadView();
  },
  methods: {
    init () {
      this.queryParams.pageSize = this.viewData.listRows;
      console.log ('viewData', this.viewData);
      var orderProps = this.viewData.properties.filter(p => p.listOrderIdx >= 0).sort(function (p1, p2) {
        return p1.listOrderIdx - p2.listOrderIdx;
      });
      console.log ('orderProps', orderProps);
      for (var i in orderProps) {
        this.orderByList.push ({
          prop : orderProps[i].id,
          order : orderProps[i].listOrderType == 'DESC' ? 'descending' : 'ascending'
        });
      }
    },
    reloadView (action) {
      this.viewData = {};
      this.listData = [];
      var me = this;
      getRvaViewData(this.viewId, this.requestParams, this,function (data, code) {
        if (code == 0) {
          me.init();
          me.getList();
        }
      })
    },
    /** 查询模块列表 */
    getList() {
      this.loading = true;
      this.queryParams.orderByList = this.orderByList;
      let params = RvaUtils.clone(this.queryParams, RvaUtils.clone(this.requestParams, {}, true), true);
      listCrud(this.viewData.loadUrl, params).then(response => {
        this.listData = response.rows;
        this.total = response.total;
        this.viewData.properties.forEach((p) => {
          if (p.formInputorData) {
            response.rows.forEach((r) => {
              if (RvaUtils.isEmpty(r[p.id])) {
                return;
              }
              listColumn(p.formInputorData, r[p.id]).then(res => {
                let names = [];
                res.rows.forEach((r2) => {
                  names.push(r2[r2.namePropId]);
                });
                r[p.id] = names.join(',');
              });
            });
          }
        });
        this.loading = false;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection;
    },
    isButtonDisabled (btn) {
      console.log ('isButtonDisabled', btn, this.selection);
      // selectType: none single singleornone multiple
      if (this.selection.length == 0) {
        if (btn.selectType.indexOf('none') >= 0) {
          return false;
        }
        return true;
      }
      if (this.selection.length == 1) {
        return false;
      }
      if (btn.selectType.indexOf('single') >= 0) {
        return true;
      }
      return false;
    },
    getPropButtonSize (p) {
      let size = 0;
      for (var i in this.listData) {
        let len = this.listData[i][p.id].length;
        if (len > size) {
          size = len;
        }
      }
      if (size > 4) {
        size = 4;
      }
      return size;
    },
    getPropButtonColSpan (p, row) {
      let size = this.getPropButtons(p, row).length;
      if (size > 4) {
        size = 4;
      }
      return 24/size;
    },
    getPropButtonColWidth (p, row) {
      let size = this.getPropButtons(r, row).length;
      if (size > 4) {
        size = 4;
      }
      return size * 75;
    },
    getPropButtons (p, row) {
      return row[p.id];
    },
    handleHeaderClass({row, column, rowIndex, columnIndex}) {
      if (column.sortable != 'custom') {
        return;
      }
      let result = this.orderByList.find(e => e.prop === column.property)
      if (result) {
        column.order = result.order;
      }
    },
    handleHeaderCLick(column) {
      if (column.sortable != 'custom') {
        return;
      }
      let orderIndex = (this.orders.indexOf(column.order) + 1) % 3;
      let result = this.orderByList.find(e => e.prop === column.property)
      if (result) {
        result.order = this.orders[orderIndex];
      } else {
        this.orderByList.push({prop:column.property, order: this.orders[orderIndex]});
      }
      this.getList();
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      let result = this.orderByList.find(e => e.prop === column.prop)
      if (result) {
        result.order = column.order;
      } else {
        this.orderByList.push({prop:column.prop, order: column.order});
      }
      this.getList();
    },
    loadList(action) {// handleRvaButtonClick中会调用
      this.getList();
    },
    /** 处理按钮点击事件 */
    handleButtonClick (data) {
      handleRvaButtonClick(this, data);
    },
    configListProperty (h, { column, $index }) {
      let prop = this.viewData.properties.filter(prop => prop.id == column.property)[0];
      return h('rva-list-config', {
        props: {
          prop
        }
      })
    }

  },
  watch: {
    queryParams: {
      handler  () {
        this.getList();
      },
      deep: true
    },
    requestParams: {
      handler () {
        this.getList();
      },
      deep: true
    },
  }
};
</script>
